/**
 * Sep 24, 2013 11:20:16 AM
 * com.kratonsolution.belian.kernel.service
 * PermissionManager.java
 */
package com.kratonsolution.belian.security.impl.service;

import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.kratonsolution.belian.kernel.service.AccessPermision;
import com.kratonsolution.belian.kernel.service.EService;
import com.kratonsolution.belian.kernel.service.Permission;

/**
 * @author Agung Dodi Perdana
 * @email agung.dodi.perdana@gmail.com
 * @Version Sinch 0.0.1
 */
@Aspect
@Component
public class PermissionManager
{
    private Logger log = Logger.getLogger(getClass());

    private static final String EMAIL_PATTERN = 
            "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    
    private Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    
    @Autowired
    private UserServiceRegistry serviceRegistry;
    
    @Before(value="@annotation(permission)")
    public void check(JoinPoint point,AccessPermision permission)
    {
        String email = null;
        
        for(Object object:point.getArgs())
        {
            if(pattern.matcher(object.toString()).matches())
            {
                email = object.toString();
                break;
            }
        }

        log.info("Checking access permission for ["+email+"]["+permission.type()+"]["+permission.serviceCode()+"]");
        
        if(!permission.type().equals(Permission.NONE))
        {
            if(Strings.isNullOrEmpty(email))
                throw new RuntimeException("illegal access for unknown user......");
            
            if(permission.serviceCode().equals(EService.NONE))
                throw new RuntimeException("No service available.......");
        
            if(!serviceRegistry.hasAccess(email, permission))
                throw new RuntimeException("Access denied,user dont have permission.");
        }
    }
}
